package com.niodata.dp.web.module.task;

import com.niodata.dp.core.ConfigurationKeys;
import com.niodata.dp.core.DpConfiguration;
import com.niodata.dp.core.exception.PermissionDeniedException;
import com.niodata.dp.core.usermgr.enums.SystemRole;
import com.niodata.dp.core.usermgr.model.UserInfo;
import com.niodata.dp.web.security.ContextUtil;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpHost;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * 代理转发.
 */
@Controller
@RequestMapping("")
public class YarnUiProxyController {

  private HttpProxyCaller proxyServlet;

  private HttpHost[] yarnRmHosts;

  @PostConstruct
  public void init() throws Exception {
    List<String> rmHosts = DpConfiguration.getStringList(ConfigurationKeys.YARN_RM_HOSTS);
    yarnRmHosts = new HttpHost[rmHosts.size()];
    for (int i = 0; i < rmHosts.size(); i++) {
      String[] hostStr = rmHosts.get(i).split(":");
      HttpHost host = new HttpHost(hostStr[0], Integer.parseInt(hostStr[1]));
      yarnRmHosts[i] = host;
    }
    proxyServlet = new HttpProxyCaller();
    proxyServlet.init();
  }

  @RequestMapping(value = "/proxy/**")
  public void map(HttpServletRequest request, HttpServletResponse response) throws Exception {

    proxyServlet.service(request, response, getActiveRm());

  }

  @RequestMapping(value = "/static/**")
  public void mapStatic(HttpServletRequest request, HttpServletResponse response) throws Exception {

    proxyServlet.service(request, response, getActiveRm());

  }

  @RequestMapping(value = "/cluster/**")
  public void mapCluster(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    UserInfo userInfo = ContextUtil.getCurrentUser();
    if (userInfo == null || !(userInfo.getRole().equals(SystemRole.ADMIN)
          || userInfo.getRole().equals(SystemRole.SUPERADMIN))) {
      throw new PermissionDeniedException("无权访问该页面");
    }
    proxyServlet.service(request, response, getActiveRm());
  }

  private HttpHost getActiveRm() {
    return yarnRmHosts[0];
  }

}
